<template>
  <el-container style="padding: 20px">
    <el-main>
      <!-- 待核查疫苗 -->
      <el-card>
        <span style="font-weight: bold; font-size: 16px">待核查疫苗</span>
        <el-table :data="tasks" style="margin-top: 20px" border>
          <el-table-column prop="numbering" label="疫苗编号" />
          <el-table-column prop="name" label="疫苗名称" />
          <el-table-column
            label="生产日期"
            :formatter="formatDateColumn('productionDate')"
          />
          <el-table-column label="操作" width="180">
            <template #default="scope">
              <el-button
                size="small"
                type="primary"
                @click="openCheckDialog(scope.row)"
              >
                核查
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>

      <!-- 已核查记录 -->
      <el-card style="margin-top: 30px">
        <span style="font-weight: bold; font-size: 16px">已核查疫苗</span>
        <el-table :data="checkedRecords" style="margin-top: 20px" border>
          <el-table-column prop="vaccineNumbering" label="疫苗编号" />
          <el-table-column label="是否合规" width="100">
            <template #default="scope">
              <el-tag :type="scope.row.flag ? 'success' : 'danger'">
                {{ scope.row.flag ? '是' : '否' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column
            label="核查时间"
            width="180"
            :formatter="formatDateColumn('checkTime')"
          />
          <el-table-column label="操作" width="100">
            <template #default="scope">
              <el-button size="small" @click="openDetail(scope.row)"
                >详细</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-card>

      <!-- 核查弹窗 -->
      <el-dialog
        title="核查疫苗"
        v-model="checkDialogVisible"
        width="400px"
        :before-close="handleCheckDialogClose"
      >
        <el-form ref="checkFormRef" :model="checkForm" label-width="80px">
          <el-form-item label="疫苗编号">
            <el-input v-model="checkForm.vaccineNumbering" disabled />
          </el-form-item>
          <el-form-item label="是否合规" required>
            <el-radio-group v-model="checkForm.flag">
              <el-radio :label="true">合规</el-radio>
              <el-radio :label="false">不合规</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="原因">
            <el-input
              type="textarea"
              v-model="checkForm.reason"
              placeholder="填写不合规原因（可选）"
              :rows="3"
            />
          </el-form-item>
        </el-form>

        <template #footer>
          <el-button @click="checkDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitCheck">提交</el-button>
        </template>
      </el-dialog>

      <!-- 详情弹窗 -->
      <el-dialog title="核查详情" v-model="detailDialogVisible" width="500px">
        <el-descriptions title="疫苗信息" :column="1" border>
          <el-descriptions-item label="疫苗编号">
            {{ detailData.vaccineNumbering }}
          </el-descriptions-item>
          <el-descriptions-item label="是否合规">
            <el-tag :type="detailData.flag ? 'success' : 'danger'">
              {{ detailData.flag ? '是' : '否' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="原因">
            {{ detailData.reason || '无' }}
          </el-descriptions-item>
          <el-descriptions-item label="核查时间">
            {{ formatDate(detailData.checkTime) }}
          </el-descriptions-item>
        </el-descriptions>

        <template #footer>
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </template>
      </el-dialog>
    </el-main>
  </el-container>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'

const checkerId = 2

const tasks = ref([])
const checkedRecords = ref([])

const checkDialogVisible = ref(false)
const detailDialogVisible = ref(false)

const checkForm = reactive({
  checkerId: checkerId,
  vaccineNumbering: '',
  flag: true,
  reason: '',
})

const detailData = ref({})

function formatDate(dateStr) {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  const y = date.getFullYear()
  const m = (date.getMonth() + 1).toString().padStart(2, '0')
  const d = date.getDate().toString().padStart(2, '0')
  return `${y}-${m}-${d}`
}

function formatDateColumn(field) {
  return (row) => formatDate(row[field])
}

async function loadPendingVaccines() {
  try {
    const res = await axios.get(
      `http://localhost:8181/api/check/pending/${checkerId}`
    )
    if (res.data.code === 0) {
      tasks.value = res.data.data
    } else {
      ElMessage.error('加载待核查疫苗失败')
    }
  } catch (error) {
    ElMessage.error('加载待核查疫苗异常')
    console.error(error)
  }
}

async function loadCheckedRecords() {
  try {
    const res = await axios.get(
      `http://localhost:8181/api/check/checked/${checkerId}`
    )
    if (res.data.code === 0) {
      checkedRecords.value = res.data.data
    } else {
      ElMessage.error('加载已核查记录失败')
    }
  } catch (error) {
    ElMessage.error('加载已核查记录异常')
    console.error(error)
  }
}

function openCheckDialog(row) {
  console.log('点击核查按钮', row)
  checkForm.vaccineNumbering = row.numbering
  checkForm.flag = true
  checkForm.reason = ''
  checkDialogVisible.value = true
}

async function submitCheck() {
  try {
    if (!checkForm.vaccineNumbering) {
      ElMessage.error('疫苗编号不能为空')
      return
    }
    const res = await axios.post(
      'http://localhost:8181/api/check/submit',
      checkForm
    )
    if (res.data.code === 0) {
      ElMessage.success('核查提交成功')
      checkDialogVisible.value = false
      await loadPendingVaccines()
      await loadCheckedRecords()
    } else {
      ElMessage.error('核查提交失败')
    }
  } catch (error) {
    ElMessage.error('核查提交异常')
    console.error(error)
  }
}

function openDetail(row) {
  console.log('点击详细按钮', row)
  detailData.value = { ...row }
  detailDialogVisible.value = true
}

function handleCheckDialogClose(done) {
  checkForm.vaccineNumbering = ''
  checkForm.flag = true
  checkForm.reason = ''
  done()
}

onMounted(() => {
  loadPendingVaccines()
  loadCheckedRecords()
})
</script>
